package model

import (
	"time"
	"user_srv/basic/config"
)

// 好友分组表
type XqFriendGroups struct {
	Id        int64     `gorm:"column:id;type:bigint;primaryKey;not null;" json:"id"`
	UserId    int64     `gorm:"column:user_id;type:bigint;not null;index;comment:所属用户ID;" json:"user_id"`
	GroupName string    `gorm:"column:group_name;type:varchar(50);not null;comment:分组名称;" json:"group_name"`
	SortOrder int32     `gorm:"column:sort_order;type:int;default:0;comment:排序;" json:"sort_order"`
	IsDefault int8      `gorm:"column:is_default;type:tinyint(1);default:0;comment:是否默认分组;" json:"is_default"`
	CreatedAt time.Time `gorm:"column:created_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"updated_at"`
}

func (x *XqFriendGroups) TableName() string { return "xq_friend_groups" }

func (x *XqFriendGroups) Create() error { return config.DB.Create(&x).Error }

func (x *XqFriendGroups) Update(where XqFriendGroups) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqFriendGroups) Delete(where XqFriendGroups) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqFriendGroups) GetDefaultGroup(userId int64) (*XqFriendGroups, error) {
	var g XqFriendGroups
	err := config.DB.Where("user_id = ? AND is_default = 1", userId).First(&g).Error
	return &g, err
}

func (x *XqFriendGroups) EnsureDefault(userId int64) (*XqFriendGroups, error) {
	g, err := x.GetDefaultGroup(userId)
	if err == nil && g.Id > 0 {
		return g, nil
	}
	def := &XqFriendGroups{UserId: userId, GroupName: "默认分组", IsDefault: 1}
	if err := def.Create(); err != nil {
		return nil, err
	}
	return def, nil
}

func (x *XqFriendGroups) ListByUser(userId int64) ([]XqFriendGroups, error) {
	var groups []XqFriendGroups
	err := config.DB.Where("user_id = ?", userId).Order("is_default DESC, sort_order ASC, id ASC").Find(&groups).Error
	return groups, err
}
